package com.hmall.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.Cilents.ItemClient;
import com.hmall.common.Cilents.UserClient;
import com.hmall.order.config.OrderIdGenerator;
import com.hmall.order.mapper.*;
import com.hmall.order.pojo.*;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order>  implements IOrderService {
    @Autowired
    private OrderIdGenerator orderIdGenerator;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;



    @Override
    public Long createOrder(Orderstock orderstock) {
        String s = orderIdGenerator.generateOrderId();
        com.hmall.common.pojo.Item selectnyid =itemClient.selectbyid(orderstock.getItemId());
        Long price = selectnyid.getPrice();
        Long l =price*orderstock.getNum();
        Order order = new Order();
        order.setTotalFee(l);
        order.setStatus(1);
        order.setId(Long.valueOf(s));
        order.setPaymentType(orderstock.getPaymentType());
        order.setUserId(Long.valueOf(2));
        orderMapper.insert(order);
        OrderDetail orderDetail = BeanUtil.toBean(selectnyid, OrderDetail.class);
        orderDetail.setOrderId(Long.valueOf(s));
        orderDetail.setItemId(orderstock.getItemId());
        orderDetail.setNum(orderstock.getNum());
        orderDetailMapper.insert(orderDetail);
        com.hmall.common.pojo.Address addressByaddressId= userClient.findAddressByaddressId(orderstock.getAddressId());
        OrderLogistics orderLogistics = BeanUtil.toBean(addressByaddressId, OrderLogistics.class);
        orderLogistics.setOrderId(Long.valueOf(s));
        orderLogistics.setMobile(addressByaddressId.getMobile());
        orderLogisticsMapper.insert(orderLogistics);
        itemClient.updateStock(orderstock.getItemId(),orderstock.getNum());
        return Long.valueOf(s);
    }
}
